import { memo, useState } from "react";

// @ts-ignore
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";

import { message, Upload } from "antd";
import type { UploadChangeParam } from "antd/es/upload";
import { UploadArticleCoverImageService } from "@/service";

import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";

import LazyLoad from "react-lazy-load";
interface IProps {
  setImageUrl: (args: any) => void;
  imageUrl: string;
  type: string;
  children?: any;
  getData?: () => void;
  other?: any;
}
const UploadFile = memo((props: IProps) => {
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const handleChange: UploadProps["onChange"] = async (
    info: UploadChangeParam<UploadFile>
  ) => {
    setLoading(true);
    // message.loading({ content: "Loading...", duration: 0 });
    const res: any = await UploadArticleCoverImageService(
      info.fileList[0].originFileObj,
      props.type
    );
    // message.destroy();
    setLoading(false);
    if (res.code === 0) {
      props.setImageUrl(res.data.url.split(",")[0]);
      props.getData?.();
      message.success(res.msg);
    } else {
      message.error(res.msg);
    }
    setFileList([]);
  };

  const beforeUpload = (file: RcFile) => {
    const isLt2M = file.size / 1024 / 1024 < 100;
    if (!isLt2M) {
      message.error("上传的图片不能大于 3 MB!");
    }
    return false;
  };
  const uploadButton = (
    <div className={"uploadButton h-72"}>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  return (
    <Upload
      name="avatar"
      listType="picture"
      className="avatar-uploader"
      fileList={fileList}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {props.children ? (
        props.children
      ) : (
        <>
          {props.imageUrl ? (
            <img className="h-full" src={props.imageUrl} alt="avatar" />
          ) : (
            uploadButton
          )}
        </>
      )}
    </Upload>
  );
});

export default UploadFile;
